package com.atguigu.daijia.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.common.constant.MqConst;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.service.RabbitService;
import com.atguigu.daijia.driver.client.DriverAccountFeignClient;
import com.atguigu.daijia.model.entity.payment.PaymentInfo;
import com.atguigu.daijia.model.enums.TradeType;
import com.atguigu.daijia.model.form.driver.TransferForm;
import com.atguigu.daijia.model.form.payment.PaymentInfoForm;
import com.atguigu.daijia.model.vo.order.OrderRewardVo;
import com.atguigu.daijia.model.vo.payment.WxPrepayVo;
import com.atguigu.daijia.order.client.OrderInfoFeignClient;
import com.atguigu.daijia.payment.mapper.PaymentInfoMapper;
import com.atguigu.daijia.payment.service.WxPayService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public WxPrepayVo createWxPayment(PaymentInfoForm paymentInfoForm) {
        try {
            // 1. 添加支付记录到支付表
            LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PaymentInfo::getOrderNo, paymentInfoForm.getOrderNo());
            PaymentInfo paymentInfo = paymentInfoMapper.selectOne(wrapper);
            if(paymentInfo == null) {
                paymentInfo = new PaymentInfo();
                BeanUtils.copyProperties(paymentInfoForm, paymentInfo);
                paymentInfo.setPaymentStatus(0);
                paymentInfo.setPayWay(paymentInfoForm.getPayWay());
                paymentInfoMapper.insert(paymentInfo);
            }

            // 2. 模拟生成微信支付参数
            WxPrepayVo wxPrepayVo = new WxPrepayVo();
            wxPrepayVo.setAppId("wx_mock_appid_" + UUID.randomUUID().toString().substring(0, 8));
            wxPrepayVo.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
            wxPrepayVo.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));
            wxPrepayVo.setPackageVal("prepay_id=" + UUID.randomUUID().toString().replaceAll("-", ""));
            wxPrepayVo.setSignType("MD5");
            wxPrepayVo.setPaySign(UUID.randomUUID().toString().replaceAll("-", ""));

            return wxPrepayVo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public Boolean queryPayStatus(String orderNo) {
        // 模拟查询支付状态
        // 这里直接返回支付成功，实际应该根据业务逻辑判断
        this.handlePayment(orderNo);
        return true;
    }

    @Override
    public void wxnotify(HttpServletRequest request) {
        // 由于是模拟支付，这里可以不做任何处理
        // 实际支付回调会在这里处理
    }

    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;

    @Autowired
    private DriverAccountFeignClient driverAccountFeignClient;

    @Override
    public void handleOrder(String orderNo) {
        //1 远程调用：更新订单状态：已经支付
        orderInfoFeignClient.updateOrderPayStatus(orderNo);

        //2 远程调用：获取系统奖励，打入到司机账户
        OrderRewardVo orderRewardVo = orderInfoFeignClient.getOrderRewardFee(orderNo).getData();
        if(orderRewardVo != null && orderRewardVo.getRewardFee().doubleValue() > 0) {
            TransferForm transferForm = new TransferForm();
            transferForm.setTradeNo(orderNo);
            transferForm.setTradeType(TradeType.REWARD.getType());
            transferForm.setContent(TradeType.REWARD.getContent());
            transferForm.setAmount(orderRewardVo.getRewardFee());
            transferForm.setDriverId(orderRewardVo.getDriverId());
            driverAccountFeignClient.transfer(transferForm);
        }
    }

    // 处理支付成功后的业务逻辑
    private void handlePayment(String orderNo) {
        // 1. 更新支付记录状态为已支付
        LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(wrapper);

        // 如果已经支付，不需要更新
        if(paymentInfo.getPaymentStatus() == 1) {
            return;
        }

        // 更新支付信息
        paymentInfo.setPaymentStatus(1);
        paymentInfo.setTransactionId("mock_trans_" + UUID.randomUUID().toString().substring(0, 16));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent("模拟支付成功");
        paymentInfoMapper.updateById(paymentInfo);

        // 2. 发送MQ消息，通知其他服务处理订单状态
        rabbitService.sendMessage(MqConst.EXCHANGE_ORDER,
                MqConst.ROUTING_PAY_SUCCESS,
                orderNo);
    }
}